/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\CustomerManage\AreaAndProducts\OperatingItemsDrawer.tsx
 * @Date: 2022-05-26 17:25:29
 * @LastEditTime: 2023-08-23 17:47:33
 */
import { http, IUdColumn, IUdFormItem, UdFilter, UdModal, UdTable, UdToolbar } from '@/lib'
import { Button, Input, message, Modal, Row } from 'antd'
import React, { Component } from 'react'
import OperatingItemsModal from './OperatingItemsModal'
import apis from '@/apis/AboutQuota'
import UdSelect from '@/components/UdFormControls/UdSelect'
import { WrappedFormUtils } from 'antd/lib/form/Form'
const confirm = Modal.confirm
interface IProps {
  record: Record<string, any>
}

interface IState {
  dataSource: Record<string, any>[]
  checkedNum: number
  selectedRowKeys: number[]
  loading: boolean
  page: number
  size: number
  total: number
  searchValues: any
}

export default class OperatingItemsDrawer extends Component<IProps, IState> {
  private filterForm: WrappedFormUtils
  private conditions: IUdFormItem[] = [
    {
      label: '品牌公司',
      id: 'brand',
      initialValue: { key: this.props.record.brandCode, label: this.props.record.brandName },
      render: (
        <UdSelect
          labelInValue
          options={this.props.record.brandNameDTOList.map(item => ({ value: item.brandCode, title: item.brandName }))}
          allowClear={false}
        />
      ),
    },
    { label: '物料名称/编码', id: 'productSearch' },
    { label: '客户名称', id: 'agentName', initialValue: this.props.record.agentName, render: <Input readOnly /> },
    { label: '客户编码', id: 'agentCode', initialValue: this.props.record.agentCode, render: <Input readOnly /> },
  ]
  private columns: IUdColumn<any>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: '50px',
      render: (text, reoled, index) => index + 1,
    },
    { title: '品牌公司', dataIndex: 'brandName', key: 'brandName', minWidth: '140px' },
    { title: '物料编号', dataIndex: 'matCode', key: 'matCode', minWidth: '140px' },
    { title: '物料名称', dataIndex: 'matName', key: 'matName', minWidth: '140px' },
    { title: '创建人工号/手机号', dataIndex: 'createCode', key: 'createCode', minWidth: '140px' },
    { title: '创建人姓名', dataIndex: 'createName', key: 'createName', minWidth: '140px' },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime', minWidth: '140px' },
  ]
  state: IState = {
    dataSource: [],
    checkedNum: 0,
    selectedRowKeys: [],
    loading: false,
    page: 1,
    size: 10,
    total: 0,
    searchValues: {},
  }

  private handAdd = () => {
    UdModal.open({
      title: '经营品项新增',
      width: '50%',
      content: <OperatingItemsModal />,
      onOk: value => {
        if (value.length > 0) {
          this.setState({ loading: true })
          let values = this.filterForm.getFieldsValue()
          let data = {
            brandCode: values.brand.key,
            brandName: values.brand.label,
            dealerCode: values.agentCode,
            dealerName: values.agentName,
            operatingItems: [],
          }
          value.forEach((item: { sapMatCode: string; matName: string }) => {
            data.operatingItems.push({ matCode: item.sapMatCode.substring(10), matName: item.matName })
          })
          http
            .post(apis.addOrUpdateOperatingMain, { ...data })
            .then(res => {
              message.success('操作成功')
              this.getRecordTableData()
            })
            .finally(() => {
              this.setState({
                loading: false,
              })
            })
        }
      },
    })
  }

  componentDidMount() {
    this.getRecordTableData()
  }

  private handleChangePage = pagination => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getRecordTableData()
    })
  }

  private handleSearch = (values: object) => {
    this.setState({ searchValues: values, page: 1 }, () => {
      this.getRecordTableData()
    })
  }

  private resetFilterHandle = (form: WrappedFormUtils) => {
    this.setState(
      { dataSource: [], selectedRowKeys: [], page: 1, total: 0, searchValues: form.getFieldsValue() },
      () => {
        this.getRecordTableData()
      }
    )
  }
  private getRecordTableData = () => {
    this.setState({ loading: true })
    let { page, size } = this.state
    let values = this.filterForm.getFieldsValue()
    http
      .post(apis.getOperatingMainPage, {
        page,
        size,
        conditions: {
          productSearch:values.productSearch,
          brandCode: values.brand.key,
          brandName: values.brand.label,
          dealerCode: values.agentCode,
          dealerName: values.agentName,
        },
      })
      .then(res => {
        const dataSource = res?.data?.content ?? []
        if (dataSource.length > 0) {
          dataSource.forEach((item: { matCode: string }) => {
            item.matCode = '0000000000' + item.matCode
          })
        }
        this.setState({
          dataSource,
          total: res.data.totalElements,
          loading: false,
        })
      })
      .finally(() => {
        this.setState({
          loading: false,
        })
      })
  }

  private onSelectChange = (selectedRowKeys: number[], selectedRows: any[]) => {
    this.setState({ selectedRowKeys })
  }

  private onSelectAll = (selected, selectedRows, changeRows) => {
    if (selected) {
      const { dataSource } = this.state
      this.setState({ selectedRowKeys: dataSource.map(({ id }) => id) })
    } else {
      this.setState({ selectedRowKeys: [] })
    }
  }

  private handDelete = () => {
    let { selectedRowKeys } = this.state
    Array.isArray(selectedRowKeys) &&
      selectedRowKeys.length > 0 &&
      confirm({
        title: '确定删除所选项吗?',
        onOk: () => {
          if (this.state.selectedRowKeys.length > 0) {
            this.setState({ loading: true })
            let ids = this.state.selectedRowKeys.join(',')
            http
              .delete(`${apis.deleteOperatingItemsById}?ids=${ids}`)
              .then(res => {
                message.success('操作成功')
                this.getRecordTableData()
              })
              .finally(() => {
                this.setState({
                  loading: false,
                  selectedRowKeys: [],
                })
              })
          }
        },
      })
  }

  render() {
    let { dataSource, selectedRowKeys, page, size, total, loading } = this.state
    return (
      <>
        <UdFilter
          items={this.conditions}
          getForm={form => {
            this.filterForm = form
          }}
          onSearch={values => {
            this.handleSearch(values)
          }}
          resetAfter={this.resetFilterHandle}
          loading={loading}
        />
        <UdToolbar
          other={
            <Row type="flex" justify="space-between">
              <Button type="danger" onClick={this.handDelete}>
                {selectedRowKeys.length > 0 ? `删除(${selectedRowKeys.length})` : '删除'}
              </Button>
              <Button type="primary" onClick={this.handAdd}>
                新增
              </Button>
            </Row>
          }
        ></UdToolbar>
        <UdTable
          rowKey="id"
          loading={loading}
          columns={this.columns}
          dataSource={dataSource}
          onChange={this.handleChangePage}
          rowSelection={{
            selectedRowKeys: selectedRowKeys,
            onChange: this.onSelectChange,
            onSelectAll: this.onSelectAll,
          }}
          pagination={{
            current: page,
            pageSize: size,
            total: total,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </>
    )
  }
}
